package lock_ban;

import xiancheng_tongxin.Product;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Stack {
    private xiancheng_tongxin.Product product;
    private boolean flag;
    public static final Lock lock = new ReentrantLock();
    public static final Condition condition_Producer = lock.newCondition();
    public static final Condition condition_Customer = lock.newCondition();
    // 创建生产方法
    public void push(Product product){
        try {
            // 如果桌子上有产品，则不能生产
            lock.lock();
            if (flag){
                try {
                    //this.wait();
                    condition_Producer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 没有产品，则生产
            // 模拟耗时
            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.product = product;
            flag = true;
            // 设置产品
            System.out.println(Thread.currentThread().getName() + "正在生产" + product.getColor()+ "的" + product.getName());
            //this.notifyAll();
            condition_Customer.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    // 创建消费方法
    public void pop(){
        lock.lock();
        try {
            if (!flag){
                try {
                    //this.wait();
                    condition_Customer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 模拟耗时
            try {
                Thread.sleep(1000);
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 消费
            flag = false;
            System.out.println(Thread.currentThread().getName() + "正在消费" + product.getColor()+ "的" + product.getName());
            //this.notifyAll();
            condition_Producer.signal();
            this.product =  null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
